package com.xfcy.blog.strategy.impl;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import com.xfcy.blog.common.enums.QiNiuAreaEnum;
import com.xfcy.blog.entity.SystemConfig;
import com.xfcy.blog.service.SystemConfigService;
import com.xfcy.blog.strategy.FileUploadStrategy;
import com.xfcy.blog.utils.UUIDUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 晓风残月Lx
 * @date 2023/5/4 16:05
 */
@Service("qiNiuUploadStrategyImpl")
public class QiNiuUploadStrategyImpl implements FileUploadStrategy {

    private final Logger logger = LoggerFactory.getLogger(QiNiuUploadStrategyImpl.class);

    @Resource
    private SystemConfigService systemConfigService;

    private String qi_niu_accessKey;

    private String qi_niu_secretKey;

    private String qi_niu_bucket;

    private Region region;

    private String qi_niu_url;

    @PostConstruct
    private void init() {
        SystemConfig systemConfig = systemConfigService.getCustomizeOne();
        qi_niu_accessKey = systemConfig.getQiNiuAccessKey();
        qi_niu_secretKey = systemConfig.getQiNiuSecretKey();
        qi_niu_bucket = systemConfig.getQiNiuBucket();
        qi_niu_url = systemConfig.getQiNiuPictureBaseUrl();
        region = QiNiuAreaEnum.getRegion(systemConfig.getQiNiuArea());
    }

    @Override
    public String fileUpload(MultipartFile file, String suffix) {
        String key = null;
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(region);
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        //...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        Auth auth = Auth.create(qi_niu_accessKey, qi_niu_secretKey);
        String upToken = auth.uploadToken(qi_niu_bucket);
        InputStream inputStream = null;

        try {
            inputStream = file.getInputStream();
            Response response = uploadManager.put(inputStream, UUIDUtils.getUuid() + "." + suffix, upToken, null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            key = qi_niu_url + putRet.key;
        } catch (QiniuException ex) {
            Response r = ex.response;
            logger.info("QiniuException:{}", r.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return key;
    }

    @Override
    public boolean deleteFile(String ...fileNames) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());//...其他参数参考类注释
        Auth auth = Auth.create(qi_niu_accessKey, qi_niu_secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        try {
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(qi_niu_bucket, fileNames);
            Response response = bucketManager.batch(batchOperations);
            BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
            for (int i = 0; i < fileNames.length; i++) {
                BatchStatus status = batchStatusList[i];
                String key = fileNames[i];
                System.out.print(key + "\t");
                if (status.code == 200) {
                    System.out.println("delete success");
                } else {
                    System.out.println(status.data.error);
                }
            }
        } catch (QiniuException ex) {
            System.err.println(ex.response.toString());
            return false;
        }
        return true;
    }

    /**
     * 获取存储的所有图片
     *
     * @return
     */
    @Override
    public List<String> getAllImages() {
        List<String> deleteKey = new ArrayList<>();
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());

        Auth auth = Auth.create(qi_niu_accessKey, qi_niu_secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);

        //文件名前缀
        String prefix = "";
        //每次迭代的长度限制，最大1000，推荐值 1000
        int limit = 1000;
        //指定目录分隔符，列出所有公共前缀（模拟列出目录效果）。缺省值为空字符串
        String delimiter = "";
        //列举空间文件列表
        BucketManager.FileListIterator fileListIterator = bucketManager.createFileListIterator(qi_niu_bucket, prefix, limit, delimiter);
        while (fileListIterator.hasNext()) {
            //处理获取的file list结果
            FileInfo[] items = fileListIterator.next();
            for (FileInfo item : items) {
                System.out.println(item.key);
                deleteKey.add(item.key);
            }
        }
        return deleteKey;
    }

}
